// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Fk
import Fk.Components.LunarLTK
import Fk.Pages.LunarLTK
import Fk.Components.Common
import QtMultimedia

GraphicsBox {
    id: root
    width: 769
    height: 429

    // 游戏状态
    property bool gameRunning: false
    property int score: 0
    property int gameTime: 25  // 游戏时间25秒
    property bool operable: false  // 是否是主机
    property bool isGuest: false   // 是否是客机
    
    // 物品类型
    property int lotus: 1
    property int thunder: 2
    
    // 物品对象
    property var items: []
    property var itemIds: ({})
    property int nextItemId: 1
    
    // 物品速度
    property real lotusSpeed: 120
    property real thunderSpeed: 150
    
    // 客机按钮冷却
    property real lotusCooldown: 0
    property real thunderCooldown: 0
    property real cooldownRate: 1  // 冷却时间1秒

    visible: root.operable || root.isGuest

    Item {
        anchors.fill: parent

        Image {
            source: "../image/anim/chongxu/bg.png"
            anchors.fill: parent
        }

        // 玩家小人
        Image {
            id: player
            property int curr: 1
            source: "../image/anim/chongxu/sunhanhua"+curr+".png"
            width: 60
            height: 115
            x: parent.width / 2 - width / 2
            y: parent.height - height - 50
            z: 10
            
            // 移动动画
            Behavior on x {
                NumberAnimation { duration: 100 }
            }
        }
        
        // 物品容器
        Item {
            id: itemContainer
            anchors.fill: parent
        }
    }
    
    // 游戏计时器
    Timer {
        id: gameTimer
        interval: 16 // 约60FPS
        running: false
        repeat: true
        onTriggered: updateGame()
    }
    
    // 游戏时间计时器
    Timer {
        id: countdownTimer
        interval: 1000
        running: false
        repeat: true
        onTriggered: {
            gameTime--;
            if (gameTime <= 0) {
                gameOver(false);
            }
        }
    }
    
    // 客机按钮冷却计时器
    Timer {
        id: cooldownTimer
        interval: 100
        running: root.isGuest && gameRunning
        repeat: true
        onTriggered: {
            if (lotusCooldown > 0) lotusCooldown -= 0.1;
            if (thunderCooldown > 0) thunderCooldown -= 0.1;
        }
    }
    
    // 更新游戏状态
    function updateGame() {
        // 移动所有物品
        for (var i = items.length - 1; i >= 0; i--) {
            var item = items[i];
            if (item.itemType === lotus) {
                item.y += lotusSpeed * 0.016; // 16ms
            }
            else {
                item.y += thunderSpeed * 0.016; // 16ms
            }
            
            if (root.operable) {
                // 检测是否被收集
                if (item.y + item.height/2 > player.y + player.height) {
                    // 移出屏幕
                    removeItem(item.objectId);
                } else if (collision(player, item)) {
                    // 碰撞检测
                    handleCollision(item);
                }
            }
        }

        // 主机随机生成物品
        if (root.operable) {
            var num = Math.random();
            if (num < 0.06) {
                if (num < 0.05) {
                    createItem(lotus);
                }
                if (num < 0.06) {
                    createItem(thunder);
                }
            }
        }
    }
    
    // 创建新物品
    function createItem(type, x = Math.random() * (root.width - 50), y = 0) {
        if (x < 120) x = 120;
        if (x > root.width - 120) x = root.width - 120;

        // 分配唯一ID
        var objectId = nextItemId++;
        
        var itemComponent;
        var itemSource;
        var itemColor;
        
        if (type === lotus) {
            itemSource = "../image/anim/chongxu/lotus"+(Math.floor(Math.random()*2)+1)+".png";
            itemColor = "#e91e63";
        } else {
            itemSource = "../image/anim/chongxu/thunder.png";
            itemColor = "#ffeb3b";
        }
        
        // 创建物品
        var item = Qt.createQmlObject(`
            import QtQuick 2.0;
            Image {
                property int objectId: ${objectId}
                property int itemType: ${type}
                source: "${itemSource}"
                width: 60
                height: 60
                x: ${x}
                y: ${y}
                z: 5
            }
        `, itemContainer);
        
        items.push(item);
        itemIds[objectId] = item;
        
        // 同步物品创建
        if (root.operable) {
            var itemData = {
                type: "create-item",
                id: objectId,
                itemType: type,
                x: x,
                y: y
            };
            ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(itemData));
        }
        
        return objectId;
    }
    
    // 移除物品
    function removeItem(objectId) {
        if (itemIds[objectId]) {
            var item = itemIds[objectId];
            
            // 同步物品移除
            if (root.operable) {
                var removeData = {
                    type: "remove-item",
                    id: objectId
                };
                ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(removeData));
            }
            
            // 移除本地物品
            item.destroy();
            delete itemIds[objectId];
            
            // 从数组中移除
            for (var i = 0; i < items.length; i++) {
                if (items[i].objectId === objectId) {
                    items.splice(i, 1);
                    break;
                }
            }
        }
    }
    
    // 碰撞检测
    function collision(obj1, obj2) {
        return obj1.x < obj2.x + obj2.width &&
               obj1.x + obj1.width > obj2.x &&
               obj1.y < obj2.y + obj2.height &&
               obj1.y + obj1.height > obj2.y;
    }
    
    // 处理碰撞
    function handleCollision(item) {
        if (item.itemType === lotus) {
            // 收集莲花
            score = Math.min(5,score + 1);
            playSound("lotus");
            
            // 同步分数变化
            if (root.operable) {
                var scoreData = {
                    type: "score-change",
                    score: score,
                    subtype: "addScore",
                };
                ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(scoreData));
            }
            
            // 检查是否获胜
            if (score >= 5) {
                score = 5
                gameOver(true);
            }
        } else {
            // 碰到落雷
            score = Math.max(0, score - 1);
            playSound("thunder");
            
            // 同步分数变化
            if (root.operable) {
                var scoreData = {
                    type: "score-change",
                    score: score,
                    subtype: "reduceScore",
                };
                ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(scoreData));
            }
        }
        
        // 移除物品
        removeItem(item.objectId);
    }
    
    // 游戏开始
    function startGame() {
        // 重置游戏状态
        gameRunning = true;
        score = 0;
        gameTime = 25;
        items = [];
        itemIds = {};
        nextItemId = 1;
        
        // 启动计时器
        gameTimer.start();
        countdownTimer.start();
        
        // 同步游戏开始
        if (root.operable) {
            var startData = {
                type: "game-start"
            };
            ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(startData));
        }
    }
    
    // 游戏结束
    function gameOver(win) {
        gameRunning = false;
        gameTimer.stop();
        countdownTimer.stop();
        
        // 同步游戏结束
        if (root.operable) {
            var endData = {
                type: "game-end",
                win: win,
                score: score
            };
            ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(endData));
        }
        
        // 显示结果
        resultOverlay.win = win;
        resultOverlay.visible = true;
    }
    
    // 移动玩家
    function movePlayer(direction) {
        if (!gameRunning || !root.operable) return;
        
        // 左右移动玩家
        var newX = player.x + (direction * 60);

        if (direction < 0) {
            leftEffect.start();
        }
        else {
            rightEffect.start();
        }
        
        // 边界检查
        if (newX < 60) newX = 60;
        if (newX > root.width - player.width - 60) newX = root.width - player.width - 60;
        
        player.x = newX;
        
        // 同步玩家位置
        var moveData = {
            type: "player-move",
            x: player.x
        };
        ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(moveData));
    }
    
    // 客机放置物品
    function guestPlaceItem(itemType) {
        if (!gameRunning || !root.isGuest) return;
        
        // 检查冷却
        if ((itemType === lotus && lotusCooldown > 0) || 
            (itemType === thunder && thunderCooldown > 0)) {
            return;
        }
        
        // 设置冷却
        if (itemType === lotus) {
            lotusCooldown = cooldownRate;
        } else {
            thunderCooldown = cooldownRate;
        }
        
        // 通知主机放置物品
        var placeData = {
            type: "guest-place",
            itemType: itemType
        };
        ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(placeData));
    }
    
    // 播放音效
    function playSound(type) {
        // 实际项目中这里会播放音效
    }

    // 控制区域 - 主机控制移动
    MouseArea {
        anchors.fill: parent
        enabled: root.operable && gameRunning
        onClicked: {
            // 点击移动玩家到该位置
            var newX = mouseX - player.width / 2;
            if (newX > player.x) {
                rightEffect.start();
                newX = player.x + 60;
            }
            else {
                leftEffect.start();
                newX = player.x - 60;
            }
            if (newX < 60) newX = 60;
            if (newX > root.width - player.width - 60) newX = root.width - player.width - 60;
            player.x = newX;
            
            // 同步玩家位置
            var moveData = {
                type: "player-move",
                x: player.x
            };
            ClientInstance.notifyServer("PushRequest", "updatemini,sync," + JSON.stringify(moveData));
        }
    }
    
    // 键盘控制 - 主机
    Keys.onLeftPressed: if (root.operable) movePlayer(-1)
    Keys.onRightPressed: if (root.operable) movePlayer(1)
    focus: true

    // 左转效果
    SequentialAnimation {
        id: leftEffect
        PropertyAnimation { target: player; property: "curr"; to: 2; duration: 50 }
    }

    // 右转效果
    SequentialAnimation {
        id: rightEffect
        PropertyAnimation { target: player; property: "curr"; to: 1; duration: 50 }
    }

    // 游戏信息显示
    Column {
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.topMargin: 30
        anchors.leftMargin: 60
        spacing: 5
        
        /*Text {
            text: root.operable ? "冲虚" : (root.isGuest ? "冲虚" : "旁观")
            font.pixelSize: 18
            color: root.operable ? "#00e676" : (root.isGuest ? "#ffab40" : "#bdbdbd")
        }*/

        Text {
            text: "总分数: " + score
            font.pixelSize: 24
            color: "white"
            style: Text.Outline
            styleColor: "black"
        }
        
        Text {
            text: "时间: " + gameTime + "秒"
            font.pixelSize: 20
            color: "#4fc3f7"
            style: Text.Outline
            styleColor: "black"
        }
    }
    
    // 客机控制面板
    Row {
        anchors.bottom: parent.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottomMargin: 60
        spacing: 30
        visible: root.isGuest
        
        Button {
            id: lotusButton
            width: 120
            height: 50
            text: "放置莲花\n冷却: " + lotusCooldown.toFixed(1) + "秒"
            enabled: lotusCooldown <= 0 && gameRunning
            onClicked: guestPlaceItem(lotus)
            
            background: Rectangle {
                color: lotusButton.enabled ? "#e91e63" : "#9c27b0"
                radius: 10
                border.color: "#d500f9"
                border.width: 2
            }
            
            contentItem: Text {
                text: parent.text
                font.pixelSize: 16
                color: "white"
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
        }
        
        Button {
            id: thunderButton
            width: 120
            height: 50
            text: "放置落雷\n冷却: " + thunderCooldown.toFixed(1) + "秒"
            enabled: thunderCooldown <= 0 && gameRunning
            onClicked: guestPlaceItem(thunder)
            
            background: Rectangle {
                color: thunderButton.enabled ? "#ffeb3b" : "#ff9800"
                radius: 10
                border.color: "#ffd600"
                border.width: 2
            }
            
            contentItem: Text {
                text: parent.text
                font.pixelSize: 16
                color: "#212121"
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
            }
        }
    }

    // 开始界面
    Rectangle {
        id: startOverlay
        anchors.fill: parent
        color: "#80000000"
        visible: !gameRunning && !resultOverlay.visible
        
        Column {
            anchors.centerIn: parent
            spacing: 20
            
            Text {
                text: "集灵"
                font.pixelSize: 72
                font.bold: true
                color: "#e91e63"
                style: Text.Outline
                styleColor: "#f8bbd0"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "收集莲花，避开落雷"
                font.pixelSize: 32
                color: "#4fc3f7"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: root.operable ? "游戏说明：\n控制人物左右移动收集莲花\n25秒内收集5朵莲花" : "游戏说明：\n放置莲花或落雷\n干扰或帮助小人收集莲花"
                font.pixelSize: 20
                color: "#ffeb3b"
                anchors.horizontalCenter: parent.horizontalCenter
                horizontalAlignment: Text.AlignHCenter
            }
            
            Button {
                text: "开始游戏"
                anchors.horizontalCenter: parent.horizontalCenter
                onClicked: startGame()
                visible: root.operable
                
                background: Rectangle {
                    color: "#4CAF50"
                    radius: 10
                }
                
                contentItem: Text {
                    text: parent.text
                    font.pixelSize: 24
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
            }
        }
    }
    
    // 结果界面
    Rectangle {
        id: resultOverlay
        anchors.fill: parent
        color: "#80000000"
        visible: false
        property bool win: false
        
        Column {
            anchors.centerIn: parent
            spacing: 30
            
            Text {
                text: "收集莲花: " + score + " / 5"
                font.pixelSize: 36
                color: "#ffeb3b"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: ["实难<br>参悟天机","实难<br>参悟天机","实难<br>参悟天机","此间奥妙<br>似有所得","此间奥妙<br>似有所得","大音希声<br>大象无形"][score]
                font.pixelSize: 60
                color: "#4fc3f7"
                style: Text.Outline
                styleColor: "#212121"
                anchors.horizontalCenter: parent.horizontalCenter
            }

            Button {
                text: "结束游戏"
                anchors.horizontalCenter: parent.horizontalCenter
                visible: root.operable
                onClicked: {
                    close();
                    roomScene.state = "notactive";
                    ClientInstance.replyToServer("", score);
                    ClientInstance.notifyServer("PushRequest", "updatemini,confirm");
                }
                
                background: Rectangle {
                    color: "#F44336"
                    radius: 10
                }
                
                contentItem: Text {
                    text: parent.text
                    font.pixelSize: 24
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
            }
        }
    }

    function loadData(data) {
        const d = data;
        operable = d[0];
        isGuest = d[1];
    }
    
    // 更新数据函数（用于客户端同步）
    function updateData(data) {
        if (data.length == 0) {
            close();
            roomScene.state = "notactive";
            ClientInstance.replyToServer("", score);
        } else {
            var parts = data.split(",");
            if (parts[0] === "sync") {
                var syncData = JSON.parse(parts.slice(1).join(","));
                
                // 处理不同类型的同步事件
                switch (syncData.type) {
                    case "game-start":{
                        // 游戏开始
                        gameRunning = true;
                        startOverlay.visible = false;
                        resultOverlay.visible = false;
                        score = 0;
                        gameTime = 25;
                        
                        // 清除旧物品
                        for (var i = 0; i < items.length; i++) {
                            items[i].destroy();
                        }
                        items = [];
                        itemIds = {};
                        nextItemId = 1;
                        
                        // 启动计时器
                        gameTimer.start();
                        countdownTimer.start();
                        break;
                    }
                    case "player-move":{
                        // 玩家移动
                        if (syncData.x < player.x) {
                            leftEffect.start();
                        }
                        else {
                            rightEffect.start();
                        }
                        player.x = syncData.x;
                        break;
                    }
                    case "create-item":{
                        // 创建物品
                        var itemType = syncData.itemType;
                        var itemSource = itemType === lotus ? 
                                          "../image/anim/chongxu/lotus"+(Math.floor(Math.random()*2)+1)+".png" : 
                                          "../image/anim/chongxu/thunder.png";
                        
                        var item = Qt.createQmlObject(`
                            import QtQuick 2.0;
                            Image {
                                property int objectId: ${syncData.id}
                                property int itemType: ${itemType}
                                source: "${itemSource}"
                                width: 60
                                height: 60
                                x: ${syncData.x}
                                y: ${syncData.y}
                                z: 5
                            }
                        `, itemContainer);
                        
                        items.push(item);
                        itemIds[syncData.id] = item;
                        break;
                    }
                    case "remove-item":{
                        // 移除物品
                        if (itemIds[syncData.id]) {
                            itemIds[syncData.id].destroy();
                            delete itemIds[syncData.id];
                            
                            // 从数组中移除
                            for (var j = 0; j < items.length; j++) {
                                if (items[j].objectId === syncData.id) {
                                    items.splice(j, 1);
                                    break;
                                }
                            }
                        }
                        break;
                    }
                    case "score-change":{
                        // 分数变化
                        score = syncData.score;
                        break;
                    }
                    case "guest-place":{
                        // 客机放置物品（主机处理）
                        if (root.operable) {
                            var x = Math.random() * (root.width - 50);
                            createItem(syncData.itemType, x, 0);
                        }
                        break;
                    }
                    case "game-end":{
                        // 游戏结束
                        gameRunning = false;
                        gameTimer.stop();
                        countdownTimer.stop();
                        resultOverlay.win = syncData.win;
                        resultOverlay.visible = true;
                        break;
                    }
                }
            }
        }
    }
    
    // 初始化游戏
    Component.onCompleted: {
        player.x = root.width / 2 - player.width / 2;
    }
}